package thread;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/17
 * <p>
 * \* Time: 10:57
 * <p>
 * \* Description:
 *      wait 和 notify、notifyAll可以实现线程间通信
 *      1、必须和synchronized一起使用 同时操作一个锁对象 执行wait 当前线程等待 并释放锁
 *      2、线程中获取锁，执行notify，会唤醒在等待池中的线程
 * \
 */
public class ThreadStateDemo {

    private static volatile Object obj = new Object();

    public static void main(String[] args) {

        new Thread1().start();
        new Thread2().start();

        System.out.println("Main >>>>>>");
    }

    static class Thread1 extends Thread {
        @Override
        public void run() {
            synchronized (obj) {
                try {
                    System.out.println("Thread1 开始执行");
                    Thread.sleep(500);
                    System.out.println("Thread1 wait");
                    obj.wait();
                    System.out.println("Thread1 结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class Thread2 extends Thread {
        @Override
        public void run() {
            synchronized (obj) {
                try {
                    System.out.println("Thread2 开始执行");
                    Thread.sleep(500);
                    System.out.println("唤醒》》》》");
                    obj.notifyAll();
                    System.out.println("Thread2 结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
